package com.zhaoc.utils;

import com.opensymphony.xwork2.ActionContext;
import com.opensymphony.xwork2.ActionSupport;
import com.opensymphony.xwork2.ModelDriven;
import org.springframework.data.domain.Page;

import java.lang.reflect.ParameterizedType;
import java.lang.reflect.Type;
import java.util.HashMap;
import java.util.Map;

/**
 * <p>title:com.zhaoc.web.base</p>
 * date:2018/8/3 0003
 * time:11:08
 * author:赵成
 * user:13566
 */
public abstract class BaseAction<T> extends ActionSupport implements ModelDriven<T> {

    //模型驱动
    protected T model;

    @Override
    public T getModel() {
        return model;
    }

    //构造器 完成model实例化
    public BaseAction(){
        //构造子类对象,获取继承父类的泛型
        Type genericSuperclass = this.getClass().getGenericSuperclass();
        //获取类型第一个泛型参数
        ParameterizedType parameterizedType = (ParameterizedType) genericSuperclass;
        Class<T> modelClass = (Class<T>) parameterizedType.getActualTypeArguments()[0];
        try {
            model = modelClass.newInstance();
        } catch (InstantiationException e) {
            e.printStackTrace();
        } catch (IllegalAccessException e) {
            e.printStackTrace();
            System.out.println("构造模型失败!");
        }
    }

    //把分页的代码加入到父类中
    //使用模型驱动获取分页数据
    protected int page;
    protected int rows;

    public void setPage(int page) {
        this.page = page;
    }

    public void setRows(int rows) {
        this.rows = rows;
    }

    protected void pushPageDataToValueStack(Page<T> pageData){
        //根据查询结果,封装gridData需要的数据格式
        Map<String, Object> result = new HashMap<String, Object>();
        result.put("total",pageData.getTotalElements());
        result.put("rows",pageData.getContent());
        //将结果压入栈顶
        ActionContext.getContext().getValueStack().push(result);
    }
}
